package gov.nih.nlm.lowlinc.core;

import java.text.NumberFormat;

import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

// http://mail-archives.apache.org/mod_mbox/logging-log4j-user/200701.mbox/%3CF32C42CCD14B994989904D3E26F7334A384BD8@gtlbmlexs0026.bagmail.net%3E
public class Log4JMemoryLayout extends PatternLayout {

	@Override
	public String format(LoggingEvent event) {
		String temp = super.format(event);

		if (event.getLevel().isGreaterOrEqual(Level.INFO)) {
			StringBuffer sbuf = new StringBuffer();

			double free = Runtime.getRuntime().freeMemory() / 1024d / 1024d / 1024;
			double max = Runtime.getRuntime().maxMemory() / 1024d / 1024d / 1024d;
			double total = Runtime.getRuntime().totalMemory() / 1024d / 1024d / 1024d;

			NumberFormat nf = NumberFormat.getNumberInstance();
			nf.setMinimumIntegerDigits(2);
			nf.setMaximumIntegerDigits(2);
			nf.setMinimumFractionDigits(1);
			nf.setMaximumFractionDigits(1);

			sbuf.append("[F: " + nf.format(free) + " ");
			sbuf.append("T: " + nf.format(total) + " ");
			sbuf.append("M: " + nf.format(max) + "] ");

			return sbuf.toString() + temp;
		} else {
			return temp;
		}
	}
}